package com.mrzhou.study.datasource;

import com.mrzhou.core.tool.utils.ClassUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Order(-1) // 保证@Transactional之前执行
@Component
public class DynamicDataSourceAspect {

    /**
     * 在方法执行前切换数据源
     */
    @Before("@annotation(com.mrzhou.study.datasource.CutDataSource) || @within(com.mrzhou.study.datasource.CutDataSource)")
    public void changeDataSource(JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature(); // // 获取方法签名(通过此签名获取目标方法信息)
        Method method = signature.getMethod(); // 获取当前动态代理的对象
        CutDataSource beforeAuth = ClassUtil.getAnnotation(method, CutDataSource.class);
        String dbid = beforeAuth.name();
        if (!DynamicDataSourceContextHolder.isContainsDataSource(dbid)) {
        } else {
            DynamicDataSourceContextHolder.setDataSourceType(dbid);
        }

    }

    @After("@annotation(com.mrzhou.study.datasource.CutDataSource)")
    public void clearDataSource(JoinPoint joinPoint) {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }

}
